package com.zl.learning.http;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.junit.Test;

import java.io.IOException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import java.util.function.Consumer;
import java.util.stream.Collectors;

public class HttpClient5 {

    public void doPost(HttpUriRequest httpPost, Consumer<CloseableHttpResponse> consumer) {
        try (CloseableHttpClient httpClient = HttpClients.createDefault();
             CloseableHttpResponse httpResponse = httpClient.execute(httpPost);) {
            consumer.accept(httpResponse);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Test
    public void test1() throws IOException {
        HttpPost httpPost = new HttpPost("http://172.31.4.130/VIID/System/Register");
        HttpEntity stringEntity = new StringEntity("{\"RegisterObject\": {\"DeviceID\": \"11010000005020000001\"}}", "UTF-8");
        httpPost.setEntity(stringEntity);
        Map<String, String> map = new HashMap<>();
        doPost(httpPost, httpResponse -> {
            for (Header header : httpResponse.getHeaders("Www-Authenticate")) {
                String val = header.getValue();
                val = val.replace("Digest", "").replaceAll("\"", "");
                Arrays.stream(val.split(",")).map(String::trim).map(r -> r.split("=")).forEach(r -> map.put(r[0], r[1]));
            }
        });
        System.out.println(map);

        String username = "test1";
        String password = "1234567a";
        String uri = "/VIID/System/Register";
        String ha1 = DigestUtils.md5Hex((username + ":" + map.get("realm") + ":" + password));
        String ha2 = DigestUtils.md5Hex(("POST:" + uri));
        String nc = "00000001";
        String cnonce = "0a4f113b";
        String response = DigestUtils.md5Hex((ha1 + ":" + map.get("nonce") + ":" + nc + ":" + cnonce + ":" + map.get("qop") + ":" + ha2));
        map.put("username", username);
        map.put("uri", uri);
        map.put("nc", nc);
        map.put("cnonce", cnonce);
        map.put("response", response);
        String val = "Digest " + map.entrySet().stream().map(r -> {
            if ("algorithm".equals(r.getKey())) {
                return r.getKey() + "=" + r.getValue();
            } else {
                return r.getKey() + "=\"" + r.getValue() + "\"";
            }
        }).collect(Collectors.joining(", "));
        System.out.println(val);
        httpPost.setHeader("Authorization", val);
        doPost(httpPost, r -> {
            try {
                System.out.println(r.getStatusLine());
                System.out.println(EntityUtils.toString(r.getEntity()));
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

}
